import React, {useEffect, useRef, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {
  ProForm, ProFormDateTimeRangePicker,
  ProFormText, ProFormTextArea
} from "@ant-design/pro-form";
import styles from './style.less';
import {Button, Card, Col, Form, message, Modal, Row, Tag} from "antd";
import {OpSpecialManager} from "@/services/api-functions";
import UploadForm from "@/components/UploadForm";
import {OssPojo, ResourcesSpecialModRequest} from "@/services/api-types";
import {history} from "umi";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {ExclamationCircleOutlined, PlusOutlined} from "@ant-design/icons";
import ResourceSelect from "@/components/ResourceSelect/ResourceSelect";
import {SYS_ENUMS} from "@/utils/constants";


export const handleResourceTopicEdit = async (fields: any, select: any, cover: OssPojo|undefined, detail: OssPojo|undefined, resources: any[]) => {
  try {
    const startTime = fields.timeRange && fields.timeRange.length > 1 ? fields.timeRange[0] : null
    const endTime = fields.timeRange && fields.timeRange.length > 1 ? fields.timeRange[1] : null
    const rpo: ResourcesSpecialModRequest = {
      id: select?.id ?? '',
      cover,
      title: fields.title,
      content: fields.content,
      detailCover: detail,
      resourcesIds: resources.map(resource=>resource.id),
      startTime,
      endTime
    }
    if (isSuccess((select && select.id ? (await OpSpecialManager.resourcesEdit(rpo)) : (await OpSpecialManager.specialAdd(rpo)))?.code)) {
      message.success('保存成功');
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

const ResourceTopicEdit: React.FC<any> = (props) => {
  const {match: {params: {id}}} = props;
  const actionRef = useRef<ActionType>();
  const [formRef] = Form.useForm()

  const [current, setCurrent] = useState<any>(null);
  const [resourceList, setResourceList] = useState<any[]>([]);
  const [cover, setCover] = useState<OssPojo>();
  const [detail, setDetail] = useState<OssPojo>();
  const [visible, setVisible] = useState<boolean>(false)

  const queryResourceTopicDetail = (id: any) => {
    OpSpecialManager.resourcesAudit(id)
      .then(({code, data})=>{
        if (isSuccess(code)) {
          setCurrent(data)
          if (data.cover) {
            setCover(data.cover)
          }
          if (data.detailCover) {
            setDetail(data.detailCover)
          }

          setResourceList(data?.resourcesResponseList??[])

          formRef?.setFieldsValue({
            title: data.title,
            cover: data.cover ? [data.cover] : [],
            detail: data.detailCover ? [data.detailCover] : [],
            content: data.content,
            timeRange: [data.startTime ?? undefined, data.endTime ?? undefined]
          })
        }
      })
  }

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 70,
      render:(dom, record, index)=> index+1

    },
    {
      title: '分类',
      dataIndex: 'classification',
      valueEnum: {
        TEMPLATE: {text: '模板'},
        WORKS: {text: '作品'},
        MATERIAL: {text: '素材'},
        ANIMATION: {text: '动画'},
        OTHER: {text: '其他'},
      },
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'sellingState',
      valueEnum: SYS_ENUMS.RESOURCE_STATUS,
      width: 100,
    },
    {
      title: '设计师',
      dataIndex: ['userDto', 'nickName'],
      ellipsis: true,
      hideInSearch: true,
      width: 150,
    },
    {
      title: '标题',
      dataIndex: 'title',
      ellipsis: true,
      width: 350,
      render: (dom, record) => {
        return (
          <a onClick={()=>history.push(`/resource/edit/${record.id}`)}>
            {dom}
          </a>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      render: (_, record: any) => [
        <a key="edit"
           onClick={() => Modal.confirm({
             title: '提示',
             icon: <ExclamationCircleOutlined/>,
             content: <span>确定要删除 <Tag color='#108ee9'>{record.title}</Tag> 吗？</span>,
             okText: '删除',
             cancelText: '取消',
             onOk: async () => removeResource(record),
           })}
        >删除</a>,
      ],
    },
  ];

  const selectResource = (resource: any) => {
    if(!resourceList.find(r=>r.id==resource.id)){
      setResourceList([...resourceList, resource])
    }
  }
  const removeResource = (resource: any) => {
    setResourceList([...resourceList.filter(r=>r.id!=resource.id)])
  }

  useEffect(() => {
    if(id){
      queryResourceTopicDetail(id)
    }
  }, [id])

  const onFinish = async (values: Record<string, any>) => {
    await handleResourceTopicEdit(values, current, cover, detail, resourceList)
  };

  return (
    <ProForm
      layout="vertical"
      hideRequiredMark
      submitter={{
        render: (props, dom) =><FooterToolbar>{dom}</FooterToolbar>,
      }}
      form={formRef}
      initialValues={{}}
      onFinish={onFinish}
      onReset={()=>{if(id){queryResourceTopicDetail(id)}else {formRef.resetFields()}}}
    >
      <PageContainer content="高级表单常见于一次性输入和提交大批量数据的场景。">
        <Card title={`${id?'编辑':'添加'}资源`} className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='标题' required rules={[{required: true, message: '请填写专题标题',},]} name="title"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormTextArea label='描述介绍' required rules={[{required: true, message: '请填写描述介绍',},]} name="content"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm name='cover' type='public' max={1} rules={[{required: true, message: '请上传封面',},]} required={true}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' label='封面' success={file => setCover(file)}
                          remove={() => setCover(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm name='detail' type='public' max={1} rules={[{required: true, message: '请上传详情图',},]} required={true}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' label='详情图' success={file => setDetail(file)}
                          remove={() => setDetail(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormDateTimeRangePicker required label='生效时间' name='timeRange'/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProTable<any, any>
                actionRef={actionRef}
                rowKey="topicResourceList"
                search={false}
                headerTitle='专题资源'
                pagination={false}
                dataSource={resourceList}
                columns={columns}
                footer={()=><Button style={{textAlign:"center", width: '100%'}} type="dashed" icon={<PlusOutlined />} onClick={()=>setVisible(true)}>添加资源</Button>}
              />
            </Col>
          </Row>
        </Card>
        <ResourceSelect visible={visible} title='选择资源' onCancel={() => setVisible(false)} onSelect={(resource: any) => selectResource(resource)} width={750}/>
      </PageContainer>
    </ProForm>
  );
};

export default ResourceTopicEdit;
